package com.ithm.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ithm.reggie.common.R;
import com.ithm.reggie.dto.OrdersDto;
import com.ithm.reggie.entity.OrderDetail;
import com.ithm.reggie.entity.Orders;
import com.ithm.reggie.service.OrderDetailService;
import com.ithm.reggie.service.OrdersService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 订单管理
 */
@Slf4j
@RestController
@RequestMapping("/order")
public class OrdersController {
    @Autowired
    private OrdersService ordersService;

    @Autowired
    private OrderDetailService orderDetailService;

    /**
     * 用户下单
     */
    @PostMapping("/submit")
    public R<String> submit(@RequestBody Orders orders) {
        log.info("订单数据：{}", orders);
        ordersService.submit(orders);


        return R.success("下单成功");
    }

    /**
     * 查看订单
     */
    @GetMapping("/userPage")
    public R<Page> userPage(int page, int pageSize) {
        //构造分页构造器对象
        Page<OrdersDto> dishDtoPage=new Page<>(page,pageSize);
        Page<Orders> pageinfo=new Page<>(page,pageSize);
        //条件构造器
        LambdaQueryWrapper<Orders> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        //添加排序条件
        lambdaQueryWrapper.orderByDesc(Orders::getOrderTime);
        ordersService.page(pageinfo,lambdaQueryWrapper);


        //处理records字段都拷贝
        BeanUtils.copyProperties(pageinfo,dishDtoPage,"records");

        List<Orders> records = pageinfo.getRecords();
        List<OrdersDto> list = records.stream().map((item -> {
            OrdersDto ordersDto = new OrdersDto();

            //拷贝除订单明细外其它字段
            BeanUtils.copyProperties(item, ordersDto);

            //查询订单明细
            Long id = item.getId();
            LambdaQueryWrapper<OrderDetail> orderDetailLambdaQueryWrapper = new LambdaQueryWrapper<>();
            orderDetailLambdaQueryWrapper.eq(OrderDetail::getOrderId, id);

            List<OrderDetail> orderDetails = orderDetailService.list(orderDetailLambdaQueryWrapper);
            ordersDto.setOrderDetails(orderDetails);

            return ordersDto;
        })).collect(Collectors.toList());

        dishDtoPage.setRecords(list);

        return R.success(dishDtoPage);
    }
}
